<template>
	<view class="add_card">
		<view class="add_card_info">
			<view class="link_lable">
				输入卡号添加
			</view>
			<uni-forms label-width="180" label-position="" :modelValue="formData" :rules="rules" ref="cardRef">
				<uni-forms-item label="银行卡号" name="code">
					<uni-easyinput :inputBorder="false" type="number" placeholderStyle="font-size:30rpx;"
						v-model="formData.code" placeholder="请输入银行卡号" maxlength="19" />
					<!-- <uni-easyinput :inputBorder="false" placeholderStyle="font-size:28rpx;" type="text"
							@iconClick="iconClick" suffixIcon="camera" v-model="formData.code" placeholder="输入银行卡号" /> -->
				</uni-forms-item>
				<template v-if="!isAddBtnShow">
					<uni-forms-item  name="name" label="银行名称">
						<uni-easyinput :inputBorder="false" placeholderStyle="font-size:30rpx;" type="text"
							v-model="formData.name" placeholder="请输入银行名称" maxlength="20" />
					</uni-forms-item>
					<uni-forms-item name="cardholderName" label="持卡人姓名">
						<uni-easyinput :inputBorder="false" placeholderStyle="font-size:30rpx;" type="text"
							v-model="formData.cardholderName" placeholder="请输入持卡人" maxlength="20" />
					</uni-forms-item>
				<!-- 	<uni-forms-item name="openingBank" label="开户行">
						<uni-easyinput :inputBorder="false" placeholderStyle="font-size:30rpx;" type="text"
							v-model="formData.openingBank" placeholder="输入开户行" maxlength="30" />
					</uni-forms-item> -->
				</template>

			</uni-forms>
		</view>
		<button class="onlogout" v-if="isAddBtnShow" @click="addCard"><span>确定</span></button>
		<button class="onlogout" v-else @click="saveCard"><span>绑定</span></button>
	</view>
</template>

<script setup lang="ts">
	import {
		ref,
		onMounted
	} from "vue";
	import apiAccount from '@/util/network_api/account.js'
	import { onUnload, onLaunch, onLoad, onHide, onShow } from '@dcloudio/uni-app'
import {findCardInfo} from "@/util/card_tool/find_card"
	onUnload(() => {
		uni.hideLoading()
	})
	const formData = ref({
		"cardholderName": "",//持卡人姓名
		"code": "",//银行卡号
		"id": '',//银行卡ID，新增不必传，修改必传
		"name": "",//	银行卡名称
		"openingBank": "",//开户行
		"type": 1//银行卡类型：银行卡类型，1：借记卡; 2：贷记卡（原信用卡大部分为贷记卡）; 3：准贷记卡; 4：预付费卡,示例值(1)
	})
	const rules = ref({
		name: {
			rules: [{
				required: true,
				errorMessage: '请填写银行名称',

			}]
		},
		cardholderName: {
			rules: [{
				required: true,
				errorMessage: '请填写持卡人姓名',
			},]
		},
		code: {
			rules: [{
				required: true,
				errorMessage: '请填写银行卡号',
			}, {
				validateFunction: function (rule, value, data, callback) {
					if (value.length < 16) {
						callback('至少输入16~19位')
					}
					if (!regTest(value.trim())) {
						callback('银行号卡号不准确')
					}
					return true
				},

			}]
		}
	})
	// 确定添加
	const isAddBtnShow = ref(true)
	const addCard = () => {
		cardRef.value?.validate().then(res => {
			isAddBtnShow.value=false
			formData.value.code=formData.value.code.trim()
			let obj:any=findCardInfo(formData.value.code)
			if(obj){
				formData.value.name=obj.name
				formData.value.type=obj.type
			}
		})
	}
	// 校验银行卡号 16~19位
	function regTest(data) {
		var regExp = /^([1-9]{1})(\d{15}|\d{18})$/;
		return regExp.test(data)
	}




	const cardRef = ref()
	const iconClick = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'], //这要注意，camera掉拍照，album是打开手机相册
			success: async (res) => {
				if (res.tempFiles[0].size / 1024 / 1024 > 4) {
					uni.showToast({
						title: '大小不能超过4M'
					})
					return
				}
				let base64 = await tempToBase64(res.tempFiles[0])
				apiAccount.bankcard({ image: base64 }).then(res2 => {
				})
			}
		});
	}
	// 保存
	const saveCard = () => {
		cardRef.value?.validate().then(res => {
			uni.showLoading({
				title: '加载中',
			});
			apiAccount.saveBankcard(formData.value).then(res => {
				if (res.code == 20000) {
					uni.hideLoading()
					uni.showToast({
						title: '添加成功！',
						icon: 'success'
					})
					setTimeout(() => {
						uni.redirectTo({
							url: "/pages_network/home/myAccount/bankCard"
						})
					}, 800)
				}
			})
		}).catch(err => {

		})
	}

	function tempToBase64(tempFiles) {
		return new Promise((resolve, reject) => {
			uni.request({
				url: tempFiles.path,
				responseType: 'arraybuffer',
				success: (res : any) => {

					// 避免获取不到文件类型
					if (!tempFiles.type) {
						uni.getImageInfo({
							src: tempFiles.path,
							success: (image) => {
								// 把arraybuffer转成base64并拼接
								// resolve(`data:image/${image.type};base64,${uni.arrayBufferToBase64(res.data)}`)
								resolve(`${uni.arrayBufferToBase64(res.data)}`)
							},
							fail: (err) => {
								reject(err)
							}
						});
					}
					// //把arraybuffer转成base64并拼接
					// else resolve(`data:${tempFiles.type};base64,${uni.arrayBufferToBase64(res.data)}`)
					else resolve(`${uni.arrayBufferToBase64(res.data)}`)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
	}
</script>

<style lang="scss" scoped>
	.add_card {
		/* #ifdef H5 */
		height: calc(100vh - 44px);
		/* #endif */
		/* #ifndef H5 */
		height: 100vh;
		/* #endif */
		display: flex;
		flex-direction: column;
		flex: 1;
		overflow: hidden;
		background-color: #fafafa;
		padding: 32rpx;
		box-sizing: border-box;
		nd-color: #fafafa;

		&_info {
			background-color: #fff;
			padding: 0 30rpx;
			box-shadow:0 0 6rpx 1rpx #eee;

			.link_lable {
				font-weight: bold;
				font-size: 28rpx;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #eee;
			}

			:deep(.uni-forms-item) {
				margin-bottom: 0 !important;
				margin-top: 1rpx;
				padding:38rpx 0;
				&~.uni-forms-item {
					border-top: 1rpx solid rgb(224, 224, 224);
				}

				.uni-input-input {
					font-size: 30rpx;
				}

				.uni-forms-item__label {
					font-size: 30rpx;
					color: #000;
					width: 180rpx;
				}
				.uni-easyinput__content{
						font-size: 30rpx;
				}
			}
		}

		.onlogout {
			font-size: 30rpx;
			margin-top: 120rpx;
			height: 80rpx;
			border-radius: 50rpx;
			line-height: 80rpx;
			width: 100%;
			color: #fff;
			background-color: #007cff;
		}

	}
</style>